<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchGetAllRoles } from '@/service/api';
import { $t } from '@/locales';
import { addGood, updateGood } from '@/service-alova/api';

defineOptions({
  name: 'OrderOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Good | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增商品',
    edit: '编辑商品'
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.SystemManage.Good,
  'goodImgUrl' | 'goodStockQuantity' | 'goodDescription' | 'goodName' | 'goodPrice' | 'goodStatus' | 'goodCategory'
>;
const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    goodName: '',
    goodDescription: '',
    goodPrice: 0,
    goodStockQuantity: 0,
    goodImgUrl: '',
    goodCategory: '',
    goodStatus: '1'
  };
}

type RuleKey = Extract<keyof Model, 'userName' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  userName: defaultRequiredRule,
  status: defaultRequiredRule
};

/** the enabled role options */
const roleOptions = ref<CommonType.Option<string>[]>([]);

async function getRoleOptions() {
  const { error, data } = await fetchGetAllRoles();

  if (!error) {
    const options = data.map(item => ({
      label: item.roleName,
      value: item.roleCode
    }));

    // the mock data does not have the roleCode, so fill it
    // if the real request, remove the following code

    // end

    roleOptions.value = [...options];
  }
}

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}
// 关闭抽屉
function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  if (props.operateType === 'edit') {
    // eslint-disable-next-line no-console
    console.log('编辑商品');
    await updateGood(model.value);
  } else if (props.operateType === 'add') {
    // eslint-disable-next-line no-console
    console.log('新增商品');
    await addGood(model.value);
  }
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
// 计算属性，用于 goodStockQuantity
const stockQuantityValue = computed({
  get() {
    return model.value.goodStockQuantity.toString(); // 将 number 转换为 string
  },
  set(value) {
    model.value.goodStockQuantity = value ? Number(value) : 0; // 将输入的 string 转换为 number，如果转换失败则默认为 0
  }
});

// 计算属性，用于 goodPrice
const priceValue = computed({
  get() {
    return model.value.goodPrice.toString(); // 将 number 转换为 string
  },
  set(value) {
    model.value.goodPrice = value ? Number(value) : 0; // 将输入的 string 转换为 number，如果转换失败则默认为 0
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="商品名字" path="goodName">
          <NInput v-model:value="model.goodName" placeholder="请输入商品名" />
        </NFormItem>
        <NFormItem label="商品分类" path="goodCategory">
          <NInput v-model:value="model.goodCategory" placeholder="请输入商品分类" />
        </NFormItem>
        <NFormItem label="介绍" path="goodDescription">
          <NInput v-model:value="model.goodDescription" placeholder="请输入介绍" />
        </NFormItem>
        <NFormItem label="价格" path="goodPrice">
          <NInput v-model:value="priceValue" placeholder="请输入价格" />
        </NFormItem>
        <NFormItem label="数量" path="goodStockQuantity">
          <NInput v-model:value="stockQuantityValue" placeholder="请输入数量" />
        </NFormItem>
        <NFormItem label="图片地址" path="goodImgUrl">
          <NInput v-model:value="model.goodImgUrl" placeholder="请输入imgurl" />
        </NFormItem>
        <NFormItem label="状态" path="goodStatus">
          <NInput v-model:value="model.goodStatus" placeholder="请输入状态" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
